﻿using AutoCommunication.Base;
using AutoCommunication.Clients;
using Furion;
using Furion.JsonSerialization;
using Furion.VirtualFileServer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;

namespace Auto.Web.Core
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddConsoleFormatter();
            services.AddControllers().AddInjectWithUnifyResult().AddNewtonsoftJson(); ;
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddBootstrapBlazor();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            var setting = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Auto };
            //List<IDevice> devices = new List<IDevice>();
            //devices.Add(new ModbusTcpClient());
            //devices.Add(new ModbusTcpClient());
            //var json = JSON.Serialize(devices, setting);
            //File.WriteAllText("DeviceList.json", json);

            var jsonstring = File.ReadAllText("DeviceList.json");
            AutoCommunication.Auto.Devices = JSON.Deserialize<List<IDevice>>(jsonstring, setting);
            AutoCommunication.Auto.DevicesConfig = JSON.Deserialize<List<IDevice>>(jsonstring, setting);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseInject();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }
    }
}